import React, { useState, useRef } from 'react'
import { useDispatch } from 'react-redux'
import { getUserProfileAction, updateUserProfile, updateUserPhotoAction } from '@/store/actions/profile'
// import type { RootState } from '@/types/store'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
// import classNames from 'classnames'
import { useInitialState } from '@/hooks/useInitialState'
import { logout } from '@/store/actions/login'

import dayjs from 'dayjs'

import EditInput from './EditInput'
import EditList from './EditList'

const Item = List.Item
const ProfileEdit = () => {
  const fileRef = useRef<HTMLInputElement>(null)
  const dispatch = useDispatch()
  // const { userProfile } = useSelector((state: RootState) => state.profile)
  const { userProfile } = useInitialState(getUserProfileAction, 'profile')
  // console.log(userProfile, 6)

  // useEffect(() => {
  //   dispatch(getUserProfileAction())
  // }, [dispatch])
  type InputState = {
    visible: boolean
    type: '' | 'name' | 'intro'
  }

  type ListState = { visible: boolean, type: '' | 'gender' | 'photo' }
  const [showList, setShowList] = useState<ListState>({
    visible: false,
    type: ''
  })
  const hideList = () => setShowList({
    type: '',
    visible: false
  })

  const [showInput, setShowInput] = useState<InputState>({
    type: '',
    visible: false
  })
  // const onUpdate2 = async (key: string, value: string) => {
  //   await dispatch(updateUserProfile(key, value))
  //   Toast.show({
  //     icon: 'success',
  //     content: '修改成功'
  //   })
  //   hideInput()
  //   hideList()
  // }
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]
    if (!file) return

    const photoData = new FormData()
    photoData.append('photo', file)
    await dispatch(updateUserPhotoAction(photoData))
    hideList()
  }

  // 关闭弹层
  const hideInput = () => {
    setShowInput({
      type: '',
      visible: false
    })
  }

  const onUpdate = async (type: string, value: string) => {
    console.log(type, value)
    if (type === 'photo') {
      fileRef.current!.click()
      return
    }
    await dispatch(updateUserProfile(type, value))
    Toast.show({
      icon: 'success',
      content: '修改成功'
    })
    hideInput()
    hideList()
  }

  const [showBirthday, setShowBirthday] = useState(false)
  const onBirthdayShow = () => {
    setShowBirthday(true)
  }
  const onBirthdayHide = () => {
    setShowBirthday(false)
  }
  const onUpdateBirthday = async (value: Date) => {
    const birthday = dayjs(value).format('YYYY-MM-DD')

    await onUpdate('birthday', birthday)
    onBirthdayHide()
  }

  const history = useHistory()

  const onLogout = () => {
    Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      closeOnAction: true,
      actions: [
        {
          key: 'close',
          text: '退出',
          onClick: () => {
            dispatch(logout())
            history.replace('/login')
            Toast.show({ content: '退出成功' })
          }
        }
      ]
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile.photo} alt="" />
                </span>
              }
              arrow
              onClick={() => setShowList({ visible: true, type: 'photo' })}
            >
              头像
            </Item>
            <Item
              arrow
              extra={userProfile.name}
              onClick={() => setShowInput({ visible: true, type: 'name' })}
            >
              昵称
            </Item>
            <Item
              arrow
              onClick={() => setShowInput({ visible: true, type: 'intro' })}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item arrow extra={userProfile.gender === 0 ? '男' : '女'} onClick={() => setShowList({ visible: true, type: 'gender' })}>
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={onBirthdayShow}>
              生日
            </Item>
            <DatePicker
              visible={showBirthday}
              value={new Date(userProfile.birthday)}
              onCancel={onBirthdayHide}
              onConfirm={onUpdateBirthday}
              title="选择年月日"
              min={new Date(1900, 0, 1, 0, 0, 0)}
              max={new Date()}
            />
          </List>
        </div>

        <div className="logout">
          <Button onClick={onLogout}>
            退出登录
          </Button>
        </div>
      </div>
      {/* <Popup visible={true} position="right">
        <div style={{ width: '100vw' }}>这里放置弹层的内容</div>
      </Popup> */}
      <Popup destroyOnClose visible={showInput.visible} position="right">
        <EditInput hideInput={() => hideInput()} type={showInput.type} onUpdate={onUpdate} />
      </Popup>

      <Popup visible={showList.visible} destroyOnClose onMaskClick={hideList}>
        <EditList type={showList.type} hideList={hideList} onUpdate={onUpdate} />
        <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
      </Popup>

    </div>
  )
}

export default ProfileEdit
